from django.http import *
from django.shortcuts import *
from django.template import Context
from google.appengine.api import users
from appengine_utilities.sessions import Session
import string
from datetime import date
from datetime import datetime
import time
import logging
import simplejson as json
from datetime import datetime
import models.users as fbusers



# HTML Escaping code begin
#
# Taken from: http://wiki.python.org/moin/EscapingHtml

html_escape_table = {
    "&": "&amp;",
    '"': "&quot;",
    "'": "&apos;",
    ">": "&gt;",
    "<": "&lt;",
    }

def html_escape(text):
    """Produce entities within text."""
    return "".join(html_escape_table.get(c,c) for c in text)

# HTML Escaping code end


def copy_dict(src, dest):
    for attribute in src:
        dest[attribute] = src[attribute]


def attributes_to_dict_no_change(obj, attributes):
    ret = { }
    for attribute in attributes:
        value = getattr(obj, attribute)
        ret[attribute] = value
    return ret


def attributes_to_dict(obj, attributes):
    ret = { }
    for attribute in attributes:
        value = getattr(obj, attribute)
        if type(value) in [date, datetime]:
            ret[attribute] = time.mktime(value.timetuple())
        elif attribute == "matchingFacts":
            newList = []
            for entry in value:
                # Convert to dict from string
                newList.append(json.loads(entry))

            value = newList
            ret[attribute] = value
        else:
            ret[attribute] = value
    return ret


def has_required_attributes(request, haystack, attributes):
    for attribute in attributes:
        if attribute not in haystack:
            # Log error
            logging.warning('Required attribute %s not found at path: %s' % \
                                (attribute, request.path))
            return False
    return True



def create_context(request, url):
    import urllib
    context = { 'request': request, 
                'urls': {}, 
                "logged_in": False, 
                "response": HttpResponse() }
    urls = context["urls"]
    urls["login"] = users.create_login_url(url)
    urls["home"]  = "/"
    urls["path"]  = url
    urls["forums"]  = "/forums/"
    urls['profile'] = '/profile/'
    if url != '/' and len(url) != 0:
        urls['profile'] += '?' + urllib.urlencode({'redirect': url})

    user = users.get_current_user()
    context["is_profile_complete"] = True
    if user is not None:
        user_id              = ''
        userEntity           = fbusers.getUserByEmailID(user.email())
        cuser = { }
        context["logged_in"] = True
        context["user"]      = cuser
        context['user']['entity'] = userEntity

        if userEntity is None:
            from md5 import md5
            context["is_profile_complete"] = False
            urls["user_home"] = "/profile/"
            cuser['emailIDmd5'] = md5(user.email()).hexdigest()
        else:
            user_id = userEntity.userID
            urls["user_home"]    = "/user/" + user_id + "/"
            cuser['emailIDmd5']  = userEntity.emailIDmd5

        cuser["nickname"]    = user.nickname()
        cuser["email"]       = user.email()
        cuser["user_id"]     = user_id
        urls["logout"]       = users.create_logout_url("/")
        

    return context


def createReturnJson(success, message=None, messageLevel=None, 
                    redirectURL=None, voidStar=None):
    import simplejson as json
    ret = { 'success': success }
    if message is not None:
        ret['message'] = message
    if messageLevel is not None:
        ret['messageLevel'] = messageLevel
    if redirectURL is not None:
        ret['redirectURL'] = redirectURL
    if voidStar is not None:
        ret['voidStar'] = voidStar
    return json.dumps(ret)

# This function ALSO check if the user is not logged in, 
# and redirects him/her appropriately
def tryToSetCookiesAndRedirect(c, response, data, requiredAttributes,
                               pathToSetCookiesOn=None):
    if pathToSetCookiesOn is None:
        pathToSetCookiesOn = c['request'].path
    if not c['logged_in'] or not c['is_profile_complete']:
        # Save the post data in the user's cookie.
        for attr in requiredAttributes:
            response.set_cookie(attr, data[attr], path=pathToSetCookiesOn)
        response.set_cookie('pendingRequest', c["request"].path)
        if not c['logged_in']:
            response.write(createReturnJson(success=False, 
                                            message="Please login to continue..", 
                                            messageLevel="info", 
                                            redirectURL=c['urls']['login']))
        else:
            response.write(createReturnJson(success=False, 
                                            message="Please update your profile to continue..", 
                                            messageLevel="info", 
                                            redirectURL=c['urls']['profile']))
                                            
        return response
    else:
        return None
